<?php
require_once 'modules/general_module.class.php';

/**
 * Clase que proporciona acceso al CMS de mFramework.
 * @author Mauro Gadaleta
 */
class baseBackoffice extends Smarty{
    /**
     * variable privada que proporciona información sobre el modulo activo del CMS
     * @access private
     * @var string
     */
	private $module;

    /**
     * objeto del modulo seleccionado
     * @access private
     * @var object
     */
	private $obj;

    /**
     * errores
     * @access private
     * @var array
     */
	private $errors = array();

    /**
     * array del menu
     * @access private
     * @var array
     */
    private $menu = array();

    /**
     * @param string $mod
     */
	function __construct($mod = "") {

		$this->module = $mod;
		
		$this->configSmarty();
		
		if(isset($_GET['logout']))
			$this->logout();
		
		if(isset($_POST['username']))
			$this->login($_POST['username'],$_POST['password']);
		
		if(!empty($this->errors))
			$this->assign('errors',$this->errors);

		if(isset($_SESSION['mFrameworkLogin']))
		{
            $user = Doctrine::getTable('MFUser')->find($_SESSION['mFrameworkLogin']['user_id']);
            if(is_object($user) && ($user->token == $_SESSION['mFrameworkLogin']['token']))
            {
                if(isset($_GET['logout']))
                    utils::redirect('?module='.CMS_MODULEDEFAULT,true,true);
                $this->chargeClassModule();
                $this->assign('loginUser',$user);
                $this->loadMenu();
			    $this->loadCMS();
            }
            else
                $this->redirectToLoginView();
		}
		else
		    $this->redirectToLoginView();
	}

    /**
     * @return void
     */
    private function redirectToLoginView() {
        if(isset($_GET['module']) || isset($_GET['action']))
            utils::redirect('?logout',true,true);
        $this->loadLogin();
    }

    /**
     * @return void
     */
	private function loadMenu() {
        $modules = utils::read_dir('../admin/modules/',1);

        foreach($modules['modules'] as $module => $array)
        {
            if(is_array($array) && $this->module!=$module)
            {
                require_once 'modules/'.$module.'/'.$module.'.class.php';
                $className = $module.'CMS';
                $mod = new $className();
                $this->setViewOrderMenu($mod);
            }
        }
        $this->setViewOrderMenu($this->obj);
        if(isset($this->menu['fixed_positions']))
            ksort($this->menu['fixed_positions']);

		$this->assign('modules',$this->menu);
	}

    /**
     * @param  $module
     * @return void
     */
    private function setViewOrderMenu($module)
    {
        if($module->active)
        {
            if(isset($module->menuOrder))
            {
                $this->menu['fixed_positions'][$module->menuOrder] = $module->module;
            }
            else
            {
                $this->menu['random_positions'][] = $module->module;
                sort($this->menu['random_positions']);
            }
        }
    }

    /**
     * @return void
     */
	private function logout() { unset($_SESSION['mFrameworkLogin']); }

    /**
     * @param  $email
     * @param  $password
     * @return void
     */
	private function login($email,$password) {
        $user = Doctrine::getTable('MfUser')->findOneByEmailAndPasswordAndCmsAccess($email,md5($password),true);
        if(is_object($user))
        {
            $_SESSION['mFrameworkLogin'] = array(
                'user_id'   => $user->id,
                'token'     => $user->token
            );
        }
        else
        {
            unset($_SESSION['mFrameworkLogin']);
            $this->errors[] = 'Autenticación incorrecta';
        }
	}

    /**
     * @return void
     */
	private function loadCMS() {
        if($this->testModules())
        {
            $path = $this->module.'/'.$this->module.'.class.php';
            if(file_exists($path))
            {
                $this->assign('module',$this->module);
            }
            else
            {
                $this->assign('module', CMS_MODULEDEFAULT);
            }

            if($_GET['action'])
                $this->assign('action',$_GET['action']);
            else
                $this->assign('action','index');

            if(!isset($_GET['display']) || $_GET['display']==1)
            {
                if(!isset($_GET['ajax']))
                    $this->display('cms.tpl');
                else
                    $this->display('ajax.tpl');
            }
        }
        else
            echo '<h1>no modules</h1>';
	}

    /**
     * @return void
     */
	private function loadLogin() {
		$this->display('login.tpl');
	}

    /**
     * @param  $module
     * @return bool
     */
    private function testModule($module) {
        $r = (is_dir('../admin/modules/'.$module))?true:false;
        return $r;
    }

    /**
     * @return bool
     */
    private function testModules() {
        $directories = scandir('../admin/modules/');
        $n = 0;
        foreach($directories as $dir)
        {
            if(strpos($dir,'.') === false)
                $n++;
        }
        $r = ($n>0)?true:false;
        return $r;
    }

    /**
     * @return void
     */
	private function chargeClassModule() {
        if($this->testModule($this->module))
        {
            require_once $this->module.'/'.$this->module.'.class.php';
            $mod = $this->module.'CMS';
            $this->obj = new $mod($this);

            $this->setId($_GET['id']);
            $this->startAction();
        }
	}

    /**
     * @param null $id
     * @return void
     */
	private function setId($id = null) { $this->obj->id = $id; }

    /**
     * @return void
     */
	private function startAction() {
        if(isset($_GET['action']))
        {
            $action = 'execute'.ucwords($_GET['action']);
            $this->obj->$action();
        }
        else
            $this->obj->executeIndex();
	}

    /**
     * @return void
     */
	private function configSmarty() {
		$this->setTemplateDir('templates');
		$this->setCompileDir('compile');
        $this->setConfigDir('config');
	}
}

?>